<style>
</style>

<div class="modal-dialog">
    <form method="post" class="form-horizontal" action="/admin/user/editzoning" data-validate="parsley">
    <input type="hidden" id="area" name="area" value="{{zoning[0].area}}">
    <input type="hidden" id="selectarea" name="selectarea" value="{{zoning[0].selectarea}}"> 
    <input type="hidden" id="tohtml" value="{{zoning[0].title}}">
    <input type="hidden" name="zoning" value="">
    <input type="hidden" name="id" value="{{id}}">
    
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">{{controller.meta_title}}</h4>
        </div>
        <div class="modal-body">
           <div class="row">
               <div class="col-md-5 scrollable"> <section class="panel panel-default" style="margin-bottom: 0"><section class="panel-body slim-scroll" data-height="370px" data-size="10px"><ul id="optarea" class="ztree"></ul></section></section></div>
               <div class="col-md-7">
                   <section class="panel panel-default " style="margin-bottom: 0">
                       <header class="panel-heading">
                           <span class="label bg-dark" id="checkCount"></span> 已选择城市
                       </header>
                       <section class="panel-body slim-scroll" data-height="330px" data-size="10px">
                           <p id="areatxt">
                           </p>
                       </section>
                   </section>
               </div>
           </div>
        </div>
        <div class="modal-footer">
            <a href="javascript:;" class="btn btn-default" data-dismiss="modal">关闭</a>
            <!-- 
            <a href="javascript:;" class="btn btn-primary btn-save">保存</a>
             -->
            <button class="btn btn-primary btn-s-md ajax-post" type="submit" target-form="form-horizontal">确定</button>
        </div>
    </div><!-- /.modal-content -->
    </form>
</div><!-- /.modal-dialog -->
<script type="text/javascript">
    $(function(){
    $.ajax({
        url:"/admin/user/optarea",
        type:"post",
        success: function(data){
            var setting = {

                view: {
                    selectedMulti: false
                },
                check: {
                    enable: true
                    //chkStyle: "radio" //单选框
                },
                data: {

                    simpleData: {
                        enable: true
                    }
                },
                callback: {
//                    beforeCheck: beforeCheck,
                    onCheck: onCheck
                }
            };
//        var data = ;
            var in_array = function(stringToSearch, arrayToSearch) {
                for (var s = 0; s < arrayToSearch.length; s++) {
                    var thisEntry = arrayToSearch[s].toString();
                    if (thisEntry == stringToSearch) {
                        return true;
                    }
                }
                return false;
            }
            var select = "{{zoning[0].selectarea}}";
            if(select.length > 2){
                select = JSON.parse(select);
                $.each(data,function(k,v){
                    if(in_array(v.id,select)){
                        v.checked=true
                    }
                    if(v.children){
                    	$.each(v.children,function(_k,_v){
                            if(in_array(_v.id,select)){
                                _v.checked=true
                            }
                            if(_v.children){
                            	$.each(_v.children,function(__k,__v){
                                    if(in_array(__v.id,select)){
                                        __v.checked=true
                                    }

                                })
                            }
                        })
                    }
                    
                })
            };
            var zNodes =data;
            var code, log, className = "dark";


            function toarr(data){
                var res = [];
                $.each(data,function(k,v){
                	if(v.children){
                		$.each(v.children,function(_k,_v){
                			if(_v.children){
                              $.each(_v.children,function(__k,__v){
                                res.push(v.id+"_"+_v.id+"_"+__v.id);
                              })
                			}else{
                				res.push(v.id+"_"+_v.id);
                			}
                        })
                	}else{
                		res.push(v.id);
                	}
                })
              return res;
            }
            function selectarea(data){
                var res = [];
                $.each(data,function(k,v){
                    res.push(v.id)
                    if(v.children){
                    	$.each(v.children,function(_k,_v){
                            res.push(_v.id)
                            if(_v.children){
                            	$.each(_v.children,function(__k,__v){
                                    res.push(__v.id)
                                })
                            }
                        })
                    }
                    
                })
                return res;
            }
            function totxt(data){
                var res = [];
                $.each(data,function(k,v){
                    res.push('<span class="text-dep1">'+v.name+'</span>');
                    
                    if(v.children){
                    	res.push("[");
                    	$.each(v.children,function(_k,_v){
                            res.push('<span class="text-dep2">'+_v.name+'</span>');
                            
                            if(_v.children&&_v.children.length < _v.chnum) {
                                res.push("(");
                                $.each(_v.children, function (__k, __v) {
                                    res.push('<span class="text-dep3">'+__v.name+'</span>');
                                })
                                res.push(")");
                            }
                        })
                        res.push("]")
                    }

                })
                return res;
            }
            function tohtml(data){
                var res = [];
                $.each(data,function(k,v){
                    res.push('<span class="text-dep1">'+v.name+'</span>');
                    if(v.children&&v.children.length < v.chnum){
                        res.push("[");
                        $.each(v.children,function(_k,_v){
                            res.push('<span class="text-dep2">'+_v.name+'</span>');
                            if(_v.children&&_v.children.length < _v.chnum) {
                                res.push("(");
                                $.each(_v.children, function (__k, __v) {
                                    res.push('<span class="text-dep3">'+__v.name+'</span>');
                                })
                                res.push(")");
                            }
                        })
                        res.push("]")
                    }
                })
                return res;
            }
            var arr_to_tree = function(data, pid) {
                var result = [], temp;
                var length=data.length;
                for(var i=0;i<length;i++) {
                    if (data[i].pid == pid) {
                        result.push(data[i]);
                        temp = arr_to_tree(data, data[i].id);
                        if (temp.length > 0) {
                            data[i].children = temp;
                        }
                    }
                }
                return result;
            }

            function onCheck(e, treeId, treeNode) {
                count();

            }

            function count() {
                var zTree = $.fn.zTree.getZTreeObj("optarea");
                var checkCount = ""
                    checkCount = zTree.getCheckedNodes(true);
                var nocheckCount = zTree.getCheckedNodes(false).length;

                $("#checkCount").text(checkCount.length);
                $("#nocheckCount").text(nocheckCount);

                localStorage.setItem('optarea', JSON.stringify(checkCount));
                var datas = arr_to_tree(JSON.parse(localStorage.getItem("optarea")),0);
                 //console.log(totxt(data).join(" "));
                
                var tohtmls =tohtml(datas).join(" ");
                $("#tohtml").val(tohtmls);
                /**
                if(tohtmls.length>0){
                    $("#{{id}}").find(".tohtml").html(tohtmls);
                }else {
                    $("#{{id}}").find(".tohtml").html('<span class="text-muted">还没有选择地区，请点击【编辑】进行添加！</span>');
                }
                */

                $("#area").val(JSON.stringify(toarr(datas)));
                $("#selectarea").val(JSON.stringify(selectarea(datas)));
                $("#areatxt").html(totxt(datas).join(" "));
                getdata();
                localStorage.removeItem("optarea");
            }
            
          
          
            function createTree() {
                $.fn.zTree.init($("#optarea"), setting, zNodes);
                count();
            }

            $(document).ready(function(){
                createTree();

            });
            $('.slim-scroll').each(function(){
                var $self = $(this), $data = $self.data(), $slimResize;
                $self.slimScroll($data);
                $(window).resize(function(e) {
                    clearTimeout($slimResize);
                    $slimResize = setTimeout(function(){$self.slimScroll($data);}, 500);
                });
                $(document).on('updateNav', function(){
                    $self.slimScroll($data);
                });
            });
        }
    });
    
  //拿数据
    function getdata(){
            var trObj={};
            var trArr = [];
            trObj.area = $("#area").val();
            trObj.selectarea = $("#selectarea").val();
            trObj.title =  $("#tohtml").val();

            trArr.push(trObj);
            console.log('trArr'+JSON.stringify(trArr));
            $("input[name='zoning']").val(JSON.stringify(trArr));
    }

    })
</script>
